package com.yuntian.service.Impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yuntian.Dto.CategoryPageQueryDto;
import com.yuntian.entity.Categories;

import com.yuntian.entity.Product;
import com.yuntian.exception.BaseException;
import com.yuntian.mapper.CategoryMapper;
import com.yuntian.result.PageResult;
import com.yuntian.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    public List<Categories> selectList() {
       return categoryMapper.selectList();
    }



    //新增
    public void insertCategory(Categories categories) {
        categories.setCreateTime(LocalDateTime.now());
        categories.setUpdateTime(LocalDateTime.now());
        Categories categories1 = categoryMapper.selectByCategoryName(categories.getCategoryName());
        if (categories1 != null){
            throw new BaseException("种类已存在");
        }
        categoryMapper.insertCategory(categories);
    }

    //修改
    public void updateCategory(Categories categories) {
        categories.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateCategory(categories);
    }

    public void deleteById(Integer id) {
        try {
            categoryMapper.deleteById(id);
        }catch(DataAccessException e){
            if(e.getRootCause() instanceof SQLException){
                System.out.println("数据库异常"+e.getRootCause().getMessage());
                throw new RuntimeException("数据库异常");
            }
        }
    }

    /**
     * 查询分类分页
     * @param categoryPageQueryDto
     * @return
     */
    public PageResult categoryList(CategoryPageQueryDto categoryPageQueryDto) {
        PageHelper.startPage(categoryPageQueryDto.getPage(),categoryPageQueryDto.getPageSize());
        Page<Categories> page = categoryMapper.categoryList(categoryPageQueryDto);
        long total = page.getTotal();
        List<Categories> result = page.getResult();
        return new PageResult(total,result);

    }

    /**
     * 统计种类数量
     * @return
     */
    @Override
    public Integer count() {
        return categoryMapper.count();
    }


}
